package com.qianyu.project.utils;

import com.qianyu.project.core.context.user.FlowUserProvider;
import com.qianyu.project.entity.SystemAuthority;
import com.qianyu.project.service.ISystemAuthorityService;
import com.qianyu.project.service.ISystemUserService;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gs
 * @date create in 2020/12/24 16:52
 */
public class AuthorityUtil {

    /**
     * description: 构建菜单 <br/>
     * author: gs   <br/>
     * date: 2020/12/24 <br/>
     * params: [systemAuthorityService] <br/>
     * return: java.util.List<com.qianyu.legal.entity.SystemAuthority>
     */
    public static List<SystemAuthority> build(ISystemAuthorityService systemAuthorityService, ISystemUserService systemUserService, FlowUserProvider flowUserProvider) {
        //查询所有根菜单
        List<SystemAuthority> rootList = systemAuthorityService.getRootList();
        //查询拥有的所有权限
        List<SystemAuthority> systemAuthorityList = systemAuthorityService.getByRole(flowUserProvider.getFlowUser().getUserRoles());
        //根据根菜单查询子菜单
        rootList.iterator().forEachRemaining(root -> {
            List<SystemAuthority> moduleList = new ArrayList<>();
            //封装模块
            systemAuthorityList.iterator().forEachRemaining(module -> {
                if(root.getId().equals(module.getAuthorityPid())){
                    moduleList.add(module);
                }
            });
            //封装模块下的菜单
            moduleList.iterator().forEachRemaining(menu -> {
                List<SystemAuthority> menuList = new ArrayList<>();
                systemAuthorityList.iterator().forEachRemaining(module -> {
                    if(menu.getId().equals(module.getAuthorityPid())){
                        menuList.add(module);
                    }
                });
                menu.setChildren(menuList);
            });
            root.setChildren(moduleList);
        });
        //返回
        return rootList;
    }
}
